package com.smart.business.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.github.pagehelper.PageHelper;
import com.smart.business.dao.ChannelDao;
import com.smart.business.dao.CollectorDao;
import com.smart.business.dao.LocalDictDao;
import com.smart.common.utils.ThreadLocalUtil;
import com.smart.entity.business.ChannelEntity;
import com.smart.entity.business.CollectChannelVO;
import com.smart.entity.business.CollectorEntity;
import com.smart.model.exception.SmartException;
import com.smart.mybatis.service.impl.BaseServiceImpl;
import com.smart.service.business.CollectorService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 采集器配置 ServiceImpl
 *
 * @author wf
 * @since 2025-07-14 16:30:22
 */
@Service("collectorService")
@Transactional(rollbackFor = Exception.class)
@RequiredArgsConstructor
public class CollectorServiceImpl extends BaseServiceImpl<CollectorDao, CollectorEntity> implements CollectorService {
    private final CollectorDao collectorDao;
    private final ChannelDao channelDao;

    @Override
    public CollectChannelVO saveCollector(CollectChannelVO collectChannelVO) {
        List<String> permissionResult = ThreadLocalUtil.getPermissionResult();
        String companyName = collectChannelVO.getCompanyName();
        Optional.ofNullable(permissionResult).filter(list -> list.contains(companyName)).orElseThrow(() -> new SmartException("请选择正确的公司"));
        Optional.ofNullable(collectChannelVO.getCollectorNumber()).orElseThrow(() -> new SmartException("请输入采集器号"));
        //将CollectChannlVO中的参数转换成ChannelEntity
        CollectorEntity collectorEntity = CollectorEntity.builder()
                .id(collectChannelVO.getId())
                .name(collectChannelVO.getName())
                .collectorNumber(collectChannelVO.getCollectorNumber())
                .companyName(companyName)
                .platInterface(collectChannelVO.getPlatInterface())
                .trafficCard(collectChannelVO.getTrafficCard())
                .awakeMode(collectChannelVO.getAwakeMode())
                .ac(collectChannelVO.getAc())
                .channelCount(collectChannelVO.getChannelCount())
                .createDate(LocalDateTime.now())
                .build();

        // 保存采集器
        boolean result = Db.save(collectorEntity);
        //获取采集器id
        String collectorId = collectorEntity.getId();

        if (result && collectChannelVO.getChannelCount() > 0 && collectChannelVO.getChannelParamList() != null) {

            List<ChannelEntity> channels = collectChannelVO.getChannelParamList().stream()
                    .peek(channel -> channel.setCollectorId(collectorId))
                    .collect(Collectors.toList());
            // 批量插入通道
            collectorDao.saveChannel(channels);
        }

        //封装返回结果
        return collectChannelVO;
    }

    @Override
    public boolean deleteCollector(List<String> deleteIds) {
        List<String> ids = collectorDao.isConnect(deleteIds);
        if (!ids.isEmpty()) {
            throw new SmartException("有设备正在使用此采集器，请先解除关联");
        }
        List<String> channelIds = collectorDao.getChannelIds(deleteIds);
        if (!channelIds.isEmpty()) {
            channelDao.deleteBatchIds(channelIds);
        }
        collectorDao.deleteBatchIds(deleteIds);

        return true;
    }

    public List<CollectorEntity> getCollectorList(String name, String code, int current, int size,String companyName) {
         PageHelper.startPage(current, size);
         return collectorDao.getCollectorList(name, code,companyName);
    }

    @Override
    public boolean saveChannelParam(ChannelEntity channelEntity) {
        int inserted = channelDao.insert(channelEntity);
        // 新增成功后，修改collector表中的channel_count字段
        Optional.of(inserted).filter(i -> i > 0).ifPresent(i -> {
            updateCollectorChannelCount(channelEntity.getCollectorId(), 1);
        });
        return true;
    }

    @Override
    public boolean deleteChannelParam(ChannelEntity channelEntity) {
        String channelId = channelEntity.getId();
        Optional.ofNullable(channelId).orElseThrow(() -> new SmartException("未找到通道参数id"));
        int deleted = channelDao.deleteById(channelId);
        // 删除成功后，修改collector表中的channel_count字段
        Optional.of(deleted).filter(i -> i > 0).ifPresent(i -> {
            updateCollectorChannelCount(channelEntity.getCollectorId(), -1);
        });
        return true;
    }

    /**
     * 更新采集器的通道计数
     * @param collectorId 采集器ID
     * @param delta 变化量（正数表示增加，负数表示减少）
     */
    private void updateCollectorChannelCount(String collectorId, int delta) {
        try {
            CollectorEntity collector = collectorDao.selectById(collectorId);
            Optional.ofNullable(collector).ifPresent(c -> {
                int newCount = c.getChannelCount() + delta;
                c.setChannelCount(newCount);
                collectorDao.updateById(c);
            });
        } catch (Exception e) {
            throw new SmartException("更新采集器通道计数失败");
        }
    }

    @Override
    public List<ChannelEntity> getChannelParamList(String collectorId) {
        if (collectorId == null) {
            throw new SmartException("参数错误");
        }
        return collectorDao.getChannelParamList(collectorId);
    }

    @Override
    public CollectChannelVO updateCollectorConfig(CollectChannelVO collectChannelVO) {
        CollectorEntity collectorEntity = CollectorEntity.builder()
                .id(collectChannelVO.getId())
                .name(collectChannelVO.getName())
                .collectorNumber(collectChannelVO.getCollectorNumber())
                .companyName(collectChannelVO.getCompanyName())
                .platInterface(collectChannelVO.getPlatInterface())
                .trafficCard(collectChannelVO.getTrafficCard())
                .awakeMode(collectChannelVO.getAwakeMode())
                .ac(collectChannelVO.getAc())
                .channelCount(collectChannelVO.getChannelCount())
                .updateDate(LocalDateTime.now())
                .build();

        // 更新采集器
        baseMapper.updateById(collectorEntity);


        // 更新通道参数：使用 collector_id + channel_number 定位
        Optional.ofNullable(collectChannelVO.getChannelParamList())
                .filter(list -> collectChannelVO.getChannelCount() > 0)
                .ifPresent(channels ->
                        channels.stream()
                                .filter(channel -> channel.getChannelNumber() != null)
                                .peek(channel -> channel.setCollectorId(collectorEntity.getId()))
                                .forEach(this::updateChannelByCollectorAndNumber)
                );

        return collectChannelVO;
    }
    public void updateChannelByCollectorAndNumber(ChannelEntity channel) {
        LambdaQueryWrapper<ChannelEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ChannelEntity::getCollectorId, channel.getCollectorId())
                .eq(ChannelEntity::getChannelNumber, channel.getChannelNumber());

        baseMapper.update(channel, wrapper);
    }



}

